package com.fypg.module.medical.service.hospitalmap;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fypg.framework.common.util.object.BeanUtils;
import com.fypg.module.medical.controller.app.map.vo.AppHospitalMapReqVo;
import com.fypg.module.medical.controller.app.map.vo.AppHospitalMapRespVo;
import com.fypg.module.medical.controller.app.map.vo.AppMapRespVO;
import com.fypg.module.medical.dal.dataobject.hospitalmap.HospitalMapDO;
import com.fypg.module.medical.dal.mysql.hospitalmap.HospitalMapMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 医院地图 Service 实现类
 *
 * @author PJY
 */
@Service
@Validated
public class HospitalMapServiceImpl implements HospitalMapService {

    @Resource
    private HospitalMapMapper hospitalMapMapper;

    @Override
    public AppMapRespVO<AppHospitalMapRespVo> getHospitalMapList(@Valid AppHospitalMapReqVo reqVO) {
        List<HospitalMapDO> hospitalMapDOList;

        if (StringUtils.isBlank(reqVO.getSearchContent())) {
            // 没有搜索内容
            hospitalMapDOList = hospitalMapMapper.selectListByConditions(reqVO);
        } else {
            // 有搜索内容
            List<HospitalMapDO> hospitalSearchResult = hospitalMapMapper.selectListByConditions(reqVO);
            List<HospitalMapDO> departmentSearchResult = hospitalMapMapper.selectListByDepartmentSearch(reqVO);

            // 使用 name 去重
            Map<String, HospitalMapDO> uniqueHospitalMap = Stream.concat(hospitalSearchResult.stream(), departmentSearchResult.stream()).collect(
                Collectors.toMap(HospitalMapDO::getName,
                    Function.identity(),
                    (existing, replacement) -> existing
                ));

            hospitalMapDOList = new ArrayList<>(uniqueHospitalMap.values());
        }

        List<AppHospitalMapRespVo> organizationMapRespVOList = BeanUtils.toBean(hospitalMapDOList, AppHospitalMapRespVo.class);
        return AppMapRespVO.<AppHospitalMapRespVo>builder()
            .list(organizationMapRespVOList)
            .total(organizationMapRespVOList.size())
            .build();
    }
}
